import Router from 'koa-router';
import { Context } from 'koa';
import { User } from '../models/User';
import { UserCharacterRelation } from '../models/UserCharacterRelation';
import { ResponseUtil } from '../utils/response';
import { validatePagination } from '../middleware/validation';
import { authenticateToken } from '../middleware/auth';
import { generateToken } from '../utils/jwt';

const router = new Router();
const userModel = new User();
const userCharacterRelationModel = new UserCharacterRelation();

/**
 * 用户登录/注册（通过微信openid）
 * POST /api/users/login
 */
router.post('/login', async (ctx) => {
  try {
    const { openid, nickname, avatar_url } = ctx.request.body;
    
    if (!openid) {
      ctx.status = 400;
      ctx.body = ResponseUtil.error(ctx, "OpenID不能为空", "BAD_REQUEST", 400);
      return;
    }

    // 查找或创建用户
    let user = await userModel.findUserByOpenid(openid);

    if (!user) {
      // 创建新用户
      if (!nickname) {
        ctx.status = 400;
        ctx.body = ResponseUtil.error(ctx, "新用户昵称不能为空", "BAD_REQUEST", 400);
        return;
      }
      
      user = await userModel.create({
        openid,
        nickname,
        avatar_url
      });
    } else {
      // 更新最后登录时间
      await userModel.updateLastLoginTime(user.id!);
      
      // 如果提供了新的昵称或头像，更新用户信息
      if (nickname && nickname !== user.nickname) {
        await userModel.updateById(user.id!, { nickname });
      }
      if (avatar_url && avatar_url !== user.avatar_url) {
        await userModel.updateById(user.id!, { avatar_url });
      }
    }
    
    // 确保user不为null
    if (!user) {
      ctx.status = 500;
      ctx.body = ResponseUtil.error(ctx, '用户创建失败', "SERVER_ERROR", 500);
      return;
    }

    // 生成JWT令牌
    const token = generateToken({ id: user.id!, openid: user.openid });

    // 返回用户信息和令牌
    ctx.body = ResponseUtil.success(ctx, {
      user: {
        id: user.id!,
        openid: user.openid,
        nickname: user.nickname,
        avatar_url: user.avatar_url,
        created_at: user.created_at
      },
      token
    }, '登录成功');
  } catch (error) {
    throw error;
  }
});

/**
 * 获取当前用户信息
 * GET /api/users/me
 */
router.get('/me', authenticateToken, async (ctx: Context) => {
  try {
    if (!ctx.user) {
      ctx.status = 401;
      ctx.body = ResponseUtil.unauthorized(ctx, '用户未认证');
      return;
    }

    const userId = ctx.user.id; // 从认证中间件获取用户ID

    const user = await userModel.findById(userId);
    
    if (!user) {
      ctx.status = 404;
      ctx.body = ResponseUtil.error(ctx, '用户不存在', 'NOT_FOUND', 404);
      return;
    }

    // 获取用户收藏统计
    const favoriteStats = await userCharacterRelationModel.getUserFavoriteStats(userId);

    ctx.body = ResponseUtil.success(ctx, {
      id: user.id!,
      openid: user.openid,
      nickname: user.nickname,
      avatar_url: user.avatar_url,
      is_active: user.is_active,
      last_login_at: user.last_login_at,
      created_at: user.created_at,
      updated_at: user.updated_at,
      stats: favoriteStats
    }, '获取用户信息成功');
  } catch (error) {
    throw error;
  }
});


export default router;